﻿using HualongExcel.Classes;
using HualongExcel.Utilities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace HualongExcel.Froms
{
    public partial class TemplateForm : Form
    {
        private static TemplateForm formIns;

        public static TemplateForm FormIns
        {
            get
            {

                if (formIns == null || formIns.IsDisposed)
                    formIns = new TemplateForm();
                return formIns;
            }
        }

        #region 字段

        #endregion

        #region 窗体方法
        public static void ShowSignleForm(bool isDialogue)
        {


            if (isDialogue)
                FormIns.ShowDialog();
            else
                FormIns.Show();

        }
        public static void HideSignleForm()
        {
            FormIns.Hide();
        }

        public static void DisposeSignleForm()
        {
            FormIns.Dispose();
        }

        public TemplateForm()
        {
            InitializeComponent();
        }

        private void TemplateForm_Load(object sender, EventArgs e)
        {
            this.Left = Screen.PrimaryScreen.Bounds.Width / 2 - this.Width / 2;//桌面的宽度的一半减去自身宽的的一半
            this.Top = Screen.PrimaryScreen.Bounds.Height / 2 - this.Height / 2;//桌面的高度的一半减去自身高度的一半
            TemplateVersionLabel.Text = $"模板版本：{TemplateConstant.buildTemplateVersion}";
        }

        #endregion

        #region 控件方法
        private void SelectPathButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "请选择模板Excel表格";
            dialog.Filter = "Excel文件(*.xlsx)|*.xlsx";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                templatePathTextBox.Text = dialog.FileName;
                if (string.IsNullOrEmpty(templateNameTextBox.Text))
                {
                    templateNameTextBox.Text = System.IO.Path.GetFileNameWithoutExtension(dialog.FileName);
                }
                MessageBox.Show("模板表格选择：" + dialog.FileName);
            }
        }

        private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MappingForm.confirmCallback = (string originCell, string targetCell) =>
            {
                mappingListBox.Items.Add($"{originCell}-{targetCell}");
            };
            MappingForm.ShowSignleForm(false, string.Empty, string.Empty);
        }



        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.mappingListBox.SelectedIndices.Count <= 0)
                return;//如果没有选择任何东西，直接返回，不执行
            MappingForm.confirmCallback = (string originCell, string targetCell) =>
            {
                for (int i = 0; i < this.mappingListBox.SelectedIndices.Count; i++)
                {
                    var index = this.mappingListBox.SelectedIndices[i];
                    mappingListBox.Items[index] = $"{originCell}-{targetCell}";
                }
            };

            var mappingInfo = this.mappingListBox.SelectedItem.ToString().Split('-');
            MappingForm.ShowSignleForm(true, mappingInfo[0], mappingInfo[1]);
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = this.mappingListBox.Items.Count - 1; i >= 0; i--)
            {
                if (this.mappingListBox.SelectedIndices.Contains(i))
                    this.mappingListBox.Items.RemoveAt(i);
            }

        }
        private void 取消选择ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mappingListBox.SelectedIndices.Clear();
            mappingListBox.SelectedItems.Clear();
            mappingListBox.SelectedIndex = -1;
            mappingListBox.SelectedItem = null;
            mappingListBox.ClearSelected();
        }

        private void mappingListBoxMenu_Opened(object sender, EventArgs e)
        {
            bool isSelectComething = mappingListBox.SelectedIndices.Count > 0;
            mappingListBoxMenu.Items[0].Enabled = !isSelectComething;
            mappingListBoxMenu.Items[1].Enabled = isSelectComething;
            mappingListBoxMenu.Items[2].Enabled = isSelectComething;
            mappingListBoxMenu.Items[3].Enabled = isSelectComething;
            mappingListBoxMenu.Items[0].Visible = !isSelectComething;
            mappingListBoxMenu.Items[1].Visible = isSelectComething;
            mappingListBoxMenu.Items[2].Visible = isSelectComething;
            mappingListBoxMenu.Items[3].Visible = isSelectComething;
        }



        private void CreatetemplateConfigButton_Click(object sender, EventArgs e)
        {
            templateData data = new templateData();
            data.templateName = templateNameTextBox.Text;
            data.templatePath = templatePathTextBox.Text;
            data.namedRule = NamedRuleTextBox.Text;
            data.mapping = new Dictionary<string, string>();//实例化映射表
            for (int i = 0; i < this.mappingListBox.Items.Count; i++)
            {
                var mapInfo = this.mappingListBox.Items[i].ToString().Split('-');
                data.mapping.Add(mapInfo[0], mapInfo[1]);//添加映射表数据
            }
            data.version = TemplateConstant.buildTemplateVersion;//传入构建的模板版本
            


            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Title = "请选择要保存的位置以及文件名";
            dialog.Filter = "json文件(*.json)|*.json";
            dialog.FileName = data.templateName;
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                TemplateHelper.Savetemplate(dialog.FileName, data);
                MessageBox.Show("保存模板至：\n" + dialog.FileName);
            }


        }

        private void LoadtemplateConfigButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "请选择模板文件";
            dialog.Filter = "json文件(*.json)|*.json";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var templateData = TemplateHelper.Loadtemplate(dialog.FileName);
                templateNameTextBox.Text = templateData.templateName;
                templatePathTextBox.Text = templateData.templatePath;
                NamedRuleTextBox.Text = templateData.namedRule;
                TemplateVersionLabel.Text = $"模板版本：{templateData.version}";
                this.mappingListBox.Items.Clear();
                foreach (var item in templateData.mapping)
                {
                    this.mappingListBox.Items.Add($"{item.Key}-{item.Value}");
                }

                MessageBox.Show("读取模板成功！：\n" + dialog.FileName);
            }
        }



        private void MappingListBox2EditText()
        {
            mappingEditTextBox.Text = string.Empty;
            StringBuilder builder = new StringBuilder();
            foreach (var item in mappingListBox.Items)
            {
                builder.AppendLine(item.ToString());
            }
            mappingEditTextBox.Text = builder.ToString();
        }

        private void MappingEditText2ListBox()
        {
          var mappinglines= mappingEditTextBox.Text.Split('\n');
            mappingListBox.Items.Clear();
            foreach (var item in mappinglines)
            {
                if (string.IsNullOrEmpty(item))
                    continue;
                mappingListBox.Items.Add(item);
            }
            
        }

        private void ListBoxToEditTextButton_Click(object sender, EventArgs e)
        {
            MappingListBox2EditText();
        }

        private void EditTextToListBoxButton_Click(object sender, EventArgs e)
        {
            MappingEditText2ListBox();
        }




        #endregion

        private void NamedRuleTextBox_TextChanged(object sender, EventArgs e)
        {
            NamedPreviewTextBox.Text = NamedRuleTextBox.Text.ReplaceVariable();
        }

        private void VariableTipsButton_Click(object sender, EventArgs e)
        {
            VariableWindow.OpenVariableWindow();
        }
    }
}

